# Name: TransCostEsalqLogDestinations.py - MCBS 01/29/2015
# Description: 

# import system module
import arcpy
from arcpy import env
from arcpy.sa import *


# Set workspace environment:
# env.workspace = "TransRaster.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\Transportation Raster\TransRaster.gdb"
PlainFolder = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\Transportation Raster"
env.overwriteOutput = True
arcpy.CheckOutExtension("Spatial")
Precision = 5000

# Data in:
MovingCost = "RoadCost" # Moving Cost data to be used
Munic      = "MunicEsalqDestination" # Municipalities centroids with columns that indicate destinations

# Get destination rasters:
Select        = [""" geocodigo_1 = 35485000 """, """ geocodigo_1 = 35187010 """, """ geocodigo_1 = 41182040 """]
Destinations  = ["Santos", "Guaruja", "Paranagua"]
SelectOrigins = [""" destsantos > 0 """, """ destguaruja > 0 """, """ destparanagua > 0 """]

arcpy.MakeFeatureLayer_management(Munic, "DestinationsLayer")

for i in [0,1,2]:
	arcpy.SelectLayerByAttribute_management("DestinationsLayer", "NEW_SELECTION", Select[i])
	Destino = "Destino" + Destinations[i]
	arcpy.FeatureToRaster_conversion("DestinationsLayer", "dummy", Destino, Precision)
	# Execute CostDistance
	outCostDistance = CostDistance(Destino, MovingCost)
	CostDestino = "Cost" + Destinations[i]
	outCostDistance.save(CostDestino)
	
	CostOrigin = "Cost2" + Destinations[i]
	CostOriginTable = "CostTable" + Destinations[i]
	arcpy.SelectLayerByAttribute_management("DestinationsLayer", "NEW_SELECTION", SelectOrigins[i])
	ExtractValuesToPoints("DestinationsLayer", CostDestino,CostOrigin,"NONE","VALUE_ONLY")
	arcpy.TableToTable_conversion(CostOrigin, PlainFolder, CostOriginTable)

# Now create table with euclidian distances:
SelectAllEsalqMunics = """ destsantos > 0 OR destguaruja > 0 OR destparanagua > 0 """
SelectDestinations   = """ geocodigo_1 = 35485000 OR geocodigo_1 = 35187010 OR geocodigo_1 = 41182040 """

NameTableEclidian = "EsalqMunicEuclidian"	
arcpy.MakeFeatureLayer_management(Munic, "EuclidianOriginLayer")	
arcpy.SelectLayerByAttribute_management("EuclidianOriginLayer", "NEW_SELECTION", SelectAllEsalqMunics)
arcpy.MakeFeatureLayer_management(Munic, "EuclidianDestinationLayer")	
arcpy.SelectLayerByAttribute_management("EuclidianDestinationLayer", "NEW_SELECTION", SelectDestinations)
arcpy.PointDistance_analysis("EuclidianOriginLayer", "EuclidianDestinationLayer", NameTableEclidian)
arcpy.TableToTable_conversion(NameTableEclidian, PlainFolder, "EsalqMunicEuclidian")
arcpy.TableToTable_conversion(Munic, PlainFolder, "AllMunicsTable")

